const { Sequelize } = require('sequelize');
const path = require('path');
const fs = require('fs').promises;
const logger = require('../utils/logger');
const { version } = require('../package.json');

async function checkInstallStatus() {
  const statusFile = path.join(__dirname, '../.install_status');
  try {
    const status = await fs.readFile(statusFile, 'utf8');
    const installInfo = JSON.parse(status);
    return {
      installed: true,
      timestamp: installInfo.timestamp,
      version: installInfo.version,
      needsUpdate: installInfo.version !== version
    };
  } catch (error) {
    return { installed: false };
  }
}

async function saveInstallStatus() {
  const statusFile = path.join(__dirname, '../.install_status');
  const status = {
    timestamp: new Date().toISOString(),
    version
  };
  await fs.writeFile(statusFile, JSON.stringify(status, null, 2));
}

async function install() {
  logger.info('检查安装状态...');
  logger.info('当前系统版本:', version);
  
  const status = await checkInstallStatus();
  if (status.installed) {
    if (status.needsUpdate) {
      logger.warn('系统需要更新:', {
        当前版本: status.version,
        最新版本: version,
        安装时间: status.timestamp
      });
      logger.info('请运行升级脚本或删除 .install_status 文件后重新安装');
    } else {
      logger.info('系统已安装且为最新版本:', {
        版本: version,
        安装时间: status.timestamp
      });
    }
    process.exit(0);
  }

  logger.info('开始安装...');

  try {
    // 1. 检查环境变量
    const envPath = path.join(__dirname, '../.env');
    if (!await fs.access(envPath).then(() => true).catch(() => false)) {
      throw new Error('找不到 .env 文件，请先配置环境变量');
    }

    // 2. 加载环境变量
    require('dotenv').config({ path: envPath });

    // 3. 检查必要的环境变量
    const requiredEnvVars = ['DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST'];
    const missingEnvVars = requiredEnvVars.filter(varName => !process.env[varName]);
    if (missingEnvVars.length > 0) {
      throw new Error(`缺少必要的环境变量: ${missingEnvVars.join(', ')}`);
    }

    // 4. 创建数据库连接
    const sequelize = new Sequelize(
      process.env.DB_NAME,
      process.env.DB_USER,
      process.env.DB_PASSWORD,
      {
        host: process.env.DB_HOST,
        dialect: 'mysql',
        logging: msg => logger.debug(msg),
        timezone: '+08:00',
        define: {
          charset: 'utf8mb4',
          collate: 'utf8mb4_unicode_ci',
          timestamps: true,
          underscored: true
        },
        dialectOptions: {
          charset: 'utf8mb4',
          dateStrings: true,
          typeCast: true
        }
      }
    );

    // 5. 测试连接
    await sequelize.authenticate();
    logger.info('数据库连接成功');

    // 6. 加载所有模型
    const models = require('../models');

    // 7. 强制更新数据库结构
    await sequelize.sync({ force: true });
    logger.info('数据库表创建完成');

    // 8. 初始化默认数据
    // 8.1 创建基础字段
    await models.Field.create({
      id: 1,
      name: '证书编号',
      field_name: 'cert_number',
      description: '证书的唯一编号',
      required: true
    });
    logger.info('默认字段创建完成');

    // 9. 创建管理员账户
    await models.Admin.createInitialAdmin();
    logger.info('管理员账户创建完成');

    // 10. 创建必要的目录
    const dirs = [
      path.join(__dirname, '../uploads'),
      path.join(__dirname, '../uploads/qrcodes'),
      path.join(__dirname, '../uploads/imports'),
      path.join(__dirname, '../uploads/exports'),
      path.join(__dirname, '../logs')
    ];

    for (const dir of dirs) {
      await fs.mkdir(dir, { recursive: true });
    }
    logger.info('系统目录创建完成');

    // 11. 保存安装状态
    await saveInstallStatus();
    logger.info('安装状态已记录');

    logger.info(`系统安装完成！版本: ${version}`);
    process.exit(0);
  } catch (error) {
    logger.error('安装失败:', error);
    process.exit(1);
  }
}

// 运行安装
install(); 